package com.cse210.grocerwe.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.DecoratedStackPanel;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.DockPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.restlet.client.resource.Result;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
@SuppressWarnings("deprecation")
public class GrocerWe implements EntryPoint {

	private final DecoratedStackPanel lists = new DecoratedStackPanel();
	private final DecoratedStackPanel shoppingList = new DecoratedStackPanel();
	private final VerticalPanel shoppingPanel = new VerticalPanel();
	private final DockPanel dock = new DockPanel();
	private final Image titleImage = new Image("grocerwe.png");
	private final Button addItem = new Button("Add Item");
	private final Button goShopping = new Button("Go Shopping");
	private final HorizontalPanel buttonPanel = new HorizontalPanel();
	private final DialogBox addItemForm = new DialogBox();
	private final VerticalPanel addItemFormPanel = new VerticalPanel();
	private final Button addItemButton = new Button("Add Item");
	private final HorizontalPanel name = new HorizontalPanel();
	private final TextBox itemName = new TextBox();
	private final HorizontalPanel category = new HorizontalPanel();
	private final ListBox categoryName = new ListBox();
	private final HorizontalPanel quantity = new HorizontalPanel();
	private final TextBox quantityNumber = new TextBox();
	private final HorizontalPanel detail = new HorizontalPanel();
	private final TextBox details = new TextBox();
	private final ListBox whichList = new ListBox();
	private final HorizontalPanel which = new HorizontalPanel();
	private final Button doneShopping = new Button("Done Shopping!");
	private final HashMap<String, String> images = new HashMap<String, String>();
	private HashMap<SGroup, ArrayList<SItem>> listNames = new HashMap<SGroup, ArrayList<SItem>>();
	private String username;
	private final DialogBox login = new DialogBox();
	private final VerticalPanel loginPanel = new VerticalPanel();
	private final HorizontalPanel namePanel = new HorizontalPanel();
	private final TextBox nameInput = new TextBox();
	private final Label nameLabel = new Label("Name: ");
	private final Button nameButton = new Button("Submit");
	private ArrayList<SItem> boughtItems = new ArrayList<SItem>();
	private final Button cancelAddItem = new Button("Cancel");
	GrocerWeProxy resource = new GrocerWeProxy();
	private final PopupPanel listChooser = new PopupPanel();
	private final VerticalPanel listChooserPanel = new VerticalPanel();
	private final HorizontalPanel listChooserButtons = new HorizontalPanel();
	private final Button listChooserSelect = new Button("Done");
	private final Button listChooserCancel = new Button("Cancel");
	private HashMap<SGroup, CheckBox> listChooserNames = new HashMap<SGroup, CheckBox>();
	private final ArrayList<SGroup> listsToBuy = new ArrayList<SGroup>();
	private final HashMap<String, ArrayList<SItem>> listsOrdered = new HashMap<String, ArrayList<SItem>>();
	private Boolean firstLoad = true;
	private Boolean debug = false;
	private final HashMap<Button, SItem> deletedItems = new HashMap<Button, SItem>();
	private final HashMap<Button, SItem> editItems = new HashMap<Button, SItem>();
	
	/**
	 * This is the entry point method. It only gets called once for 
	 * every time the application runs.
	 */
	public void onModuleLoad() {
		//Login - ensure that the user name is correct, get all groups/items and then load the home page
		nameButton.addClickListener(new ClickListener() {
			@Override
			public void onClick(Widget sender) {
				//Check to make sure they input a username
				if(nameInput.getText() == null || nameInput.getText().equals(""))
				{
					if(debug)
						Window.alert("Please enter your username");
					nameInput.setText("");
				}
				//Check to make sure they input a proper email address
				else if(checkUsername(nameInput.getText()))
				{
					if(debug)
						Window.alert("Invalid username");
					nameInput.setText("");
				}
				//The username is correct
				else
				{
					username = nameInput.getText();
					nameInput.setText("");
					//Set up the popup for adding an item once
					login.hide();
					loadHome();
				}
			}
		});
		
		namePanel.add(nameLabel);
		namePanel.add(nameInput);
		loginPanel.add(namePanel);
		loginPanel.add(nameButton);
		login.add(loginPanel);
		login.show();

		images.put("grocerwe1", "gabby.png");
		images.put("grocerwe3", "haro.png");
		images.put("grocerwe4", "franklin.png");
		images.put("grocerwe2", "suman.png");
		images.put("grocerwe5", "jon.png");
		
		buttonPanel.add(addItem);
		buttonPanel.add(goShopping);
		RootPanel.get().add(dock);
		
		//Handling "add item" start, no db calls because we aren't sure 
		//if the user is actually adding an item yet
		addItem.addClickListener(new ClickListener(){

			@Override
			public void onClick(Widget sender) {
				addItemForm.center();
				addItemForm.show();
			}});
		
		//Handling "cancel item add" but doesn't call the db
		cancelAddItem.addClickListener(new ClickListener(){
			@Override
			public void onClick(Widget sender) {
				
				itemName.setText("");
				quantityNumber.setText("");
				details.setText("");
				whichList.setSelectedIndex(0);
				categoryName.setSelectedIndex(0);
				addItemForm.hide();
			}});
		
		//Handling "add item" submission, db calls are handled in addItem() and loadHome()
		addItemButton.addClickListener(new ClickListener(){
			@Override
			public void onClick(Widget sender) {
				addItem();
			}});
		
		listChooserSelect.addClickListener(new ClickListener(){
			@Override
			public void onClick(Widget sender) {
				Set<SGroup> names = listChooserNames.keySet();
				Iterator<SGroup> it = names.iterator();
				while(it.hasNext())
				{
					SGroup group = it.next();
					if(debug)
						Window.alert("Did they chose list: "+group.getName()+" ?");
					if(listChooserNames.get(group).isChecked())
					{
						if(debug)
							Window.alert("Chose list: "+group.getName());
						//boolean ret2 = claimList(group);
						//if(debug && !ret2)
							//Window.alert("Error: claim list returned false");
						//else
						claimList(group);
							listsToBuy.add(group);
					}
				}				
				
				listChooser.hide();
				shop();
			}
		});
		listChooserCancel.addClickListener(new ClickListener(){
			@Override
			public void onClick(Widget sender) {
				Set<SGroup> groups = listChooserNames.keySet();
				Iterator<SGroup> it = groups.iterator();
				while(it.hasNext())
				{
					SGroup group = it.next();
					listChooserNames.get(group).setChecked(false);
				}
				listChooser.hide();
			}
		});
		//Handling "go shopping", db calls are handled in the shop() method
		goShopping.addClickListener(new ClickListener(){

			@Override
			public void onClick(Widget sender) {
				if(debug)
					Window.alert("About to show list chooser!");
				listChooser.show();
			}});
		
		//Handling "done shopping", but db calls are called in methods not here
		doneShopping.addClickListener(new ClickListener(){

			@Override
			public void onClick(Widget sender) {
				
				updateBoughtItems();
			}});
	}
	

	private void claimList(SGroup group)
	{ 
		if(debug)
			Window.alert("Going to try to claim list: "+group.getName());
		resource.claimList(getGroupKey(group.getName()), username, new Result<Void>() {
			public void onFailure(Throwable caught)
			{
				if(debug)
					Window.alert("Could not claim the list");
			}
			public void onSuccess(Void v)
			{	
				if(debug)
					Window.alert("Claimed the list");
			}
		});
	}
	/* makes sure the username is one of the ones that is stored in the db */
	private boolean checkUsername(String un)
	{
		return !un.equals("grocerwe1") && !un.equals("grocerwe2") && !un.equals("grocerwe3") && !un.equals("grocerwe4") && !un.equals("grocerwe5");
	}
	
	/* Gets the key for the group so that it can be retrieved later */
	private String getGroupKey(String groupName)
	{
		Set<SGroup> groupnames = listNames.keySet();
		Iterator<SGroup> it = groupnames.iterator();
		while(it.hasNext())
		{
			SGroup group = it.next();
			if(group.getName().equals(groupName))
				return group.getKey();
		}
		return null;
	}
	
	/* inserting an item into a list */
	private void insertItem(String groupName, SItem item)
	{
		Set<SGroup> groupnames = listNames.keySet();
		Iterator<SGroup> it = groupnames.iterator();
		while(it.hasNext())
		{
			SGroup group = it.next();
			if(group.getName().equals(groupName))
				listNames.get(group).add(item);	
		}
	}
	
	/*
	 * Add an item - gather all ther information from the
	 * Need to send information tot he DB
	 */
	private void addItem()
	{
		if(debug)
			Window.alert("About to add the item");
		String groupKey = getGroupKey(whichList.getItemText(whichList.getSelectedIndex()));
		if(debug)
			Window.alert("Got group key: "+groupKey);
//		boolean incorrect = true;
//		while(incorrect)
//		{
//			if(itemName.getText().equals(""))
//				Window.alert("Please input a proper item name");
//			else if(quantityNumber.getText().equals(""))
//				Window.alert("Please input a Quantity Number");
//			else if(details.getText().equals(""))
//				Window.alert("Please input details about your item");
//			else
//				incorrect = false;
//		}
		SItem i = new SItem(itemName.getText(), categoryName.getItemText(categoryName.getSelectedIndex()), 
				quantityNumber.getText(), details.getText(), username, groupKey);
		if(debug)
			Window.alert("just created the item");
		
		insertItem(whichList.getItemText(whichList.getSelectedIndex()), i);
		if(debug)
			Window.alert("Adding item: "+i.getName());
		itemName.setText("");
		quantityNumber.setText("");
		details.setText("");
		whichList.setSelectedIndex(0);
		categoryName.setSelectedIndex(0);
		if(debug)
			Window.alert("Trying to add");
		//Callback: Send this item to the backend
		resource.addItem(i, new Result<Void>() {
			public void onFailure(Throwable caught)
			{
				if(debug)
					Window.alert("Failed to add the item");
			}
			public void onSuccess(Void v)
			{
				if(debug)
					Window.alert("Success!");
				addItemForm.hide();
				loadHome();
			}
		});
	}
	
	/*
     * Update the items that were bought
     */
    private void updateBoughtItems()
    {
    	resource.purchaseItems(boughtItems, new Result<Void>() {
			public void onFailure(Throwable caught)
			{
				if(debug)
					Window.alert("Failed to purchase items");
			}
			public void onSuccess(Void v)
			{
				if(debug)
					Window.alert("Successfully bought items, going to load home now");
				final int size = listsToBuy.size();
				
				for(int i = 0; i < size; i++)
				{
					final SGroup group = listsToBuy.get(i);
					if(debug)
						Window.alert("Going to try to claim list: "+group.getName());
					resource.releaseList(getGroupKey(group.getName()), username, new Result<Void>() {
						public void onFailure(Throwable caught)
						{
							if(debug)
								Window.alert("Could not release the list");
						}
						public void onSuccess(Void v)
						{	
							if(debug)
								Window.alert("Released the list: "+group.getName());
						
							if(listsToBuy.indexOf(group) == (size-1))
							{
								if(debug)
									Window.alert("Done releasing all the lists");
								loadHome();
							}
						}
					});
				}
			}
		});
    }
    
    /* Given a group name, find the actual group associated with it */
	private SGroup getGroup(String groupName)
	{
		Set<SGroup> groupnames = listNames.keySet();
		Iterator<SGroup> it = groupnames.iterator();
		while(it.hasNext())
		{
			SGroup group = it.next();
			if(group.getName().equals(groupName))
				return group;
		}
		return null;
	}
	
	/* Given a group key, find the group object associated with it */
	private SGroup getGroupFromKey(String groupKey)
	{
		if(debug)
			Window.alert("in getGroupFromKey: "+groupKey);
		Set<SGroup> groupnames = listNames.keySet();
		Iterator<SGroup> it = groupnames.iterator();
		while(it.hasNext())
		{
			SGroup group = it.next();
			if(debug)
				Window.alert("checking group: "+group.getName());
			if(group.getKey().equals(groupKey))
				return group;
		}
		if(debug)
			Window.alert("returning null");
		return null;
	}                            
    
    /*
     * Retrieves all the data from the database and populates the lists on the home page
     */
	private void loadHome()
	{
		if(debug)
			Window.alert("Clearing the lists");
		listNames = new HashMap<SGroup, ArrayList<SItem>>();
		if(debug)
			Window.alert("Done Clearing lists");
		
		//Get all the group names that are associated with this user
		resource.getGroups(username, new Result<SGroup[]>() {
			public void onFailure(Throwable caught)
			{
				if(debug)
					Window.alert("Failed getting the groups");
			}
			public void onSuccess(SGroup[]groups)
			{
				for( SGroup group : groups)
				{
					//Add each group with an empty array list to the listNames hashmap
					listNames.put(group, new ArrayList<SItem>());
				}
				SGroup pfm = new SGroup();
				pfm.setName("Purchased For Me");
				
				SGroup pbm = new SGroup();
				pbm.setName("Purchased By Me");
				
				//Add the purchased groups to the listnames hashmap
				listNames.put(pfm, new ArrayList<SItem>());
				listNames.put(pbm, new ArrayList<SItem>());
				
				resource.getAllItems(username, new Result<SItem[]>() {
					public void onFailure(Throwable caught)
					{
						if(debug)
							Window.alert("Could not get the items for this user: "+username + "\n error\n"+caught.toString());
					}
					public void onSuccess(SItem[] items)
					{									
						for(int i = 0; i < items.length; i++)
						{
							if(debug)
							{
								Window.alert("Found another item: "+items[i].getName());
								Window.alert("item group key: "+items[i].getGroup());
								Window.alert("item group: "+getGroupFromKey(items[i].getGroup()).getName());
								Window.alert("item owner : "+items[i].getOwner());
								Window.alert("item buyer: "+items[i].getBuyer());
								Window.alert("item type: "+items[i].getType());
							}
							SItem item = items[i];
							if(item.getBuyer() != null && item.getOwner().equals(username))
							{
								if(debug)
									Window.alert("Purchased For Me group");
								SGroup curr = getGroup("Purchased For Me");
								if (curr != null)
									listNames.get(curr).add(item);
							}
							else if(item.getBuyer() != null && item.getOwner() != null && item.getBuyer().equals(username) && !item.getOwner().equals(username))
							{
								if(debug)
									Window.alert("Purchased By Me group");
								SGroup curr = getGroup("Purchased By Me");
								if (curr != null)
									listNames.get(curr).add(item);
							}
							else if(item.getBuyer() != null && item.getOwner() != null && !item.getBuyer().equals(username) && !item.getOwner().equals(username))
							{
								if(debug)
									Window.alert("This item was bought by someone else for someone else");
							}
							else if(getGroupFromKey(item.getGroup()) == null)
							{
								if(debug)
									Window.alert("NOT MY ITEM!");
							}
							else
							{
								if(debug)
									Window.alert("Other group: "+getGroupFromKey(item.getGroup()).getName());
								SGroup curr = getGroupFromKey(item.getGroup());
								if (curr != null)
									listNames.get(curr).add(item);
							}
						}
						if(firstLoad)
						{
							firstLoad = false;
							addItemSetup();
							chooseLists();
						}
						lists.clear();
						lists.setWidth("300px");
						Set<SGroup> groups = listNames.keySet();
						Iterator<SGroup> it = groups.iterator();
						
						while(it.hasNext())
						{
							SGroup group = it.next();
							if(debug)
								Window.alert("adding to the ui group: "+group.getName());
							ArrayList<SItem> i = listNames.get(group);
							VerticalPanel panel = new VerticalPanel();
							for(final SItem is : i)
							{
								if(debug)
									Window.alert("Item found: "+is.getName());
								HorizontalPanel h = new HorizontalPanel();
								Image image = new Image(images.get(is.getOwner()));
								image.setWidth("25px");
								image.setHeight("25px");
								String s = is.getName();
								if(is.getDescription() != null)
									s += " - " + is.getDescription();
								if(is.getQuantitySize() != null)
									s += " - " + is.getQuantitySize();
								Label l = new Label(s);
								if(is.isLocked())
									l.setStyleName("label");
								h.add(image);
								h.add(l);
								Button editItem = new Button("Edit");
								editItem.addClickHandler(new ClickHandler(){
									SItem item = is;
									@Override
									public void onClick(ClickEvent event) {
										if(debug)
											Window.alert("editing item: "+item.getName());
										editItemSetup(item, item.getName(),item.getType(), item.getDescription(), getGroupFromKey(item.getGroup()).getName(), item.getQuantitySize());
									}});
								Button deleteItem = new Button("Delete");
								deleteItem.addClickHandler(new ClickHandler(){
									SItem item = is;
									@Override
									public void onClick(ClickEvent event) {
										if(debug)
											Window.alert("deleting item: "+item.getName() + " and the key: "+item.getKey());
										
										resource.removeItem(item.getKey(), new Result<Void>() {
											public void onFailure(Throwable caught)
											{
												if(debug)
													Window.alert("Could not delete the item: "+item.getName());
												loadHome();
											}
											public void onSuccess(Void v)
											{	
												if(debug)
													Window.alert("Deleted the item: "+item.getName());
												loadHome();
											}
										});
									}});
								if(!is.isLocked() && !getGroupFromKey(is.getGroup()).equals("Purchased For Me") && !getGroupFromKey(is.getGroup()).equals("Purchased By Me"))
								{
									h.add(editItem);
									h.add(deleteItem);
								}
								else if(getGroupFromKey(is.getGroup()).equals("Purchased By Me"))
								{
									h.add(deleteItem);
								}
								panel.add(h);
							}
							lists.add(panel, group.getName(), true);
						}
					
						titleImage.setWidth("300px");
						
						dock.clear();
						dock.add(titleImage, DockPanel.NORTH);
						dock.add(lists, DockPanel.CENTER);
						dock.add(buttonPanel, DockPanel.SOUTH);
					}
				});
			}
		});
	}
	
	
	/*
	 * Setting up the add item form, actually adding the item happens in the button listener
	 * No DB calls needed
	 */
	private void addItemSetup()
	{
		name.add(new Label("Name"));
		name.add(itemName);
		addItemFormPanel.add(name);
		
		category.add(new Label("Category"));
		categoryName.addItem("Dairy");
		categoryName.addItem("Produce");
		categoryName.addItem("Bakery");
		categoryName.addItem("Meat");
		categoryName.addItem("Breakfast");
		categoryName.addItem("Other");
		category.add(categoryName);
		addItemFormPanel.add(category);
		
		which.add(new Label("List"));
		
		Set<SGroup> groupnames = listNames.keySet();
		Iterator<SGroup> it = groupnames.iterator();
		while(it.hasNext())
		{
			SGroup group = it.next();
			String groupname = group.getName();
			if(!groupname.equals("Purchased By Me") && !groupname.equals("Purchased For Me"))
				whichList.addItem(groupname);
		}
		
		which.add(whichList);
		addItemFormPanel.add(which);
		
		quantity.add(new Label("Quantity"));
		quantity.add(quantityNumber);
		addItemFormPanel.add(quantity);
		
		detail.add(new Label("Details"));
		detail.add(details);
		addItemFormPanel.add(detail);
		
		HorizontalPanel h = new HorizontalPanel();
		h.add(addItemButton);
		h.add(cancelAddItem);
		
		addItemFormPanel.add(h);
		addItemForm.setGlassEnabled(true);
		addItemForm.setAnimationEnabled(true);
		
		addItemForm.add(addItemFormPanel);
	}
	
	private void editItemSetup(final SItem item, String name, String category, String details, String list, String quantity)
	{
		if(debug)
			Window.alert("trying to edit the item");
		final DialogBox editItemForm = new DialogBox();
		
		HorizontalPanel namePanel = new HorizontalPanel();
		namePanel.add(new Label("Name"));
		final TextBox nameBox = new TextBox();
		nameBox.setText(name);
		namePanel.add(nameBox);
		VerticalPanel editItemFormPanel = new VerticalPanel();
		editItemFormPanel.add(namePanel);
		
		HorizontalPanel categoryPanel = new HorizontalPanel();
		categoryPanel.add(new Label("Category"));
		final ListBox categoryChooser = new ListBox();
		categoryChooser.addItem("Dairy");
		categoryChooser.addItem("Produce");
		categoryChooser.addItem("Bakery");
		categoryChooser.addItem("Meat");
		categoryChooser.addItem("Breakfast");
		categoryChooser.addItem("Other");
		if(category.equals("Dairy"))
			categoryChooser.setSelectedIndex(0);
		else if(category.equals("Produce"))
			categoryChooser.setSelectedIndex(1);
		else if(category.equals("Bakery"))
			categoryChooser.setSelectedIndex(2);
		else if(category.equals("Meat"))
			categoryChooser.setSelectedIndex(3);
		else if(category.equals("Breakfast"))
			categoryChooser.setSelectedIndex(4);
		else if(category.equals("Other"))
			categoryChooser.setSelectedIndex(5);
		categoryPanel.add(categoryChooser);
		editItemFormPanel.add(categoryPanel);
		
		HorizontalPanel groupPanel = new HorizontalPanel();
		groupPanel.add(new Label("List"));
		
		final ListBox groupChooser = new ListBox();
		
		Set<SGroup> groupnames = listNames.keySet();
		Iterator<SGroup> it = groupnames.iterator();
		int i = 0;
		while(it.hasNext())
		{
			SGroup group = it.next();
			String groupname = group.getName();
			if(!groupname.equals("Purchased By Me") && !groupname.equals("Purchased For Me"))
				groupChooser.addItem(groupname);
			if(groupname.equals(list))
				groupChooser.setSelectedIndex(i);
			else
				i++;
		}
		
		groupPanel.add(groupChooser);
		editItemFormPanel.add(groupPanel);
		
		HorizontalPanel quantityPanel = new HorizontalPanel();
		quantityPanel.add(new Label("Quantity"));
		final TextBox quantityBox = new TextBox();
		quantityBox.setText(quantity);
		quantityPanel.add(quantityBox);
		editItemFormPanel.add(quantityPanel);
		
		HorizontalPanel detailPanel = new HorizontalPanel();
		detailPanel.add(new Label("Details"));
		final TextBox detailBox = new TextBox();
		detailBox.setText(details);
		detailPanel.add(detailBox);
		editItemFormPanel.add(detailPanel);
		
		HorizontalPanel h = new HorizontalPanel();
		Button editItemSubmit = new Button("Submit");
		editItemSubmit.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {

				item.setDescription(detailBox.getText());
				item.setName(nameBox.getText());
				item.setGroup(getGroupKey(groupChooser.getItemText(groupChooser.getSelectedIndex())));
				item.setType(categoryChooser.getItemText(categoryChooser.getSelectedIndex()));
				item.setQuantitySize(quantityBox.getText());
				
				resource.editItem(item, new Result<Void>() {
					public void onFailure(Throwable caught)
					{
						editItemForm.hide();
						if(debug)
							Window.alert("Could not edit the item: "+item.getName());
					}
					public void onSuccess(Void v)
					{	
						editItemForm.hide();
						if(debug)
							Window.alert("Edited item: "+item.getName());
						loadHome();
					}
				});
				
			}});
		Button editItemCancel = new Button("Cancel");
		editItemCancel.addClickHandler(new ClickHandler(){

			@Override
			public void onClick(ClickEvent event) {
				if(debug)
					Window.alert("Canceling editing the item");				
			}});
		h.add(editItemSubmit);
		h.add(editItemCancel);
		
		editItemFormPanel.add(h);
		
		editItemForm.setGlassEnabled(true);
		editItemForm.setAnimationEnabled(true);
		
		editItemForm.add(editItemFormPanel);
		if(debug)
			Window.alert("about to show the form");
		editItemForm.show();
	}
	
	/*
	 * Choose lists to shop for
	 */
	private void chooseLists()
	{
		if(debug)
			Window.alert("Choose Lists");

		listChooserButtons.add(listChooserSelect);
		listChooserButtons.add(listChooserCancel);
		
		Set<SGroup> names = listNames.keySet();
		Iterator<SGroup> it = names.iterator();
		while(it.hasNext())
		{
			SGroup group = it.next();
			if(debug)
				Window.alert("Found group: "+group.getName());
			if(!group.getName().equals("Purchased By Me") && !group.getName().equals("Purchased For Me"))
			{
				CheckBox cb = new CheckBox(group.getName());
				listChooserNames.put(group, cb);
				listChooserPanel.add(cb);
				if(debug)	
					Window.alert("Added the group to the panel");
			}
		}		
		VerticalPanel p = new VerticalPanel();
		if(debug)
			Window.alert("Adding them to the p panel");
		p.add(listChooserPanel);
		if(debug)
			Window.alert("Just added the p panel");
		p.add(listChooserButtons);
		if(debug)
			Window.alert("adding to the listChooser");
		listChooser.add(p);
		if(debug)
			Window.alert("Done setting up the list chooser");
	}
	
	private void sortItems(ArrayList<SItem> items)
	{
		if(debug)
			Window.alert("Sorting the items");
		ArrayList<SItem> produce = new ArrayList<SItem>();
		ArrayList<SItem> dairy = new ArrayList<SItem>();
		ArrayList<SItem> other = new ArrayList<SItem>();
		ArrayList<SItem> bakery = new ArrayList<SItem>();
		ArrayList<SItem> meat = new ArrayList<SItem>();
		ArrayList<SItem> breakfast = new ArrayList<SItem>();
		
		for(SItem item : items)
		{
			if(debug)
				Window.alert("Item to sort: "+item.getName() + "and its type: "+item.getType());
			if(item.getType().equals("Produce"))
				produce.add(item);
			else if(item.getType().equals("Dairy"))
				dairy.add(item);
			else if(item.getType().equals("Meat"))
				meat.add(item);
			else if(item.getType().equals("Bakery"))
				bakery.add(item);
			else if(item.getType().equals("Breakfast"))
				breakfast.add(item);
			else
				other.add(item);
		}
		
		listsOrdered.clear();
		listsOrdered.put("Produce", produce);
		listsOrdered.put("Dairy", dairy);
		listsOrdered.put("Other", other);
		listsOrdered.put("Bakery", bakery);
		listsOrdered.put("Breakfast", breakfast);
		listsOrdered.put("Meat", meat);
	}
	
	/*
	 * Bringing up the window to go shopping
	 * Need to notify the db that they are shopping 
	 */
	private void shop()
	{
		//listsToBuy
		
		shoppingList.setWidth("300px");
		shoppingList.add(shoppingPanel, "Shopping List", true);
		
		boughtItems.clear();
		shoppingPanel.clear();
		ArrayList<SItem> items = new ArrayList<SItem>();
		
		for(SGroup list : listsToBuy)
		{
			if(debug)
				Window.alert("Getting items for list: "+list.getName());
			items.addAll(listNames.get(list));
		}
		
		sortItems(items);
		
		Set<String> listsorderednames = listsOrdered.keySet();
		Iterator<String> it = listsorderednames.iterator();
		
		while(it.hasNext())
		{
			String listname = it.next();
			
			ArrayList<SItem> listitems = listsOrdered.get(listname);
			if(listitems.size() > 0)
			{
				if(debug)
					Window.alert("adding list: "+listname+" to the UI");
				Label category = new Label(listname);
				shoppingPanel.add(category);
				
			
				for(final SItem item : listitems)
				{
					if(debug)
						Window.alert("Adding item: "+item.getName());
					HorizontalPanel h = new HorizontalPanel();
					Image i = new Image(images.get(item.getOwner()));
					i.setWidth("25px");
					i.setHeight("25px");
					String s = item.getName();
					if(item.getDescription() != null)
						s += " - " + item.getDescription();
					if(item.getQuantitySize() != null)
						s += " - " + item.getQuantitySize();
					Label l = new Label(s);
					
					h.add(i);
					h.add(l);
					CheckBox cb = new CheckBox();
					cb.addClickHandler(new ClickHandler(){
		
						@Override
						public void onClick(ClickEvent event) {
							if(boughtItems.contains(item))
							{
								boughtItems.remove(item);
								item.setBuyer(null);
							}
							else
							{
								item.setBuyer(username);
								boughtItems.add(item);
							}
						}});
					
					h.add(cb);
					shoppingPanel.add(h);
				}
			}
		}
		
		dock.clear();
		
		dock.add(shoppingPanel, DockPanel.CENTER);
		dock.add(doneShopping, DockPanel.SOUTH);
	}
}
